package com.readaloud.wicket;

import java.io.Serializable;
import java.util.List;


import org.apache.wicket.Component;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextArea;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.LoadableDetachableModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;

import com.readaloud.hibernate.user.Author;
import com.readaloud.hibernate.user.Books;

public class AuthorHomePage extends WebPage{

	AuthorHomePage(Author author){
		add(new AuthorHomePageForm("authorHomePageForm",author));
	}
	
	private class AuthorHomePageForm extends Form<Component> {
		private Author author;

		public AuthorHomePageForm(String id, Author author) {
			super(id);
			this.author = author;
			IModel<Author> authorBookModel = new LoadableDetachableModel() {
				protected Author load() {
					return WicketApplication.get().getInvertedIndexDao()
							.getAuthorDetails(getAuthorId());
				}
			};
			setDefaultModel(authorBookModel);
			add(new Label("authorName",new PropertyModel<String>(getDefaultModel(), "authorName")));
			TextArea biography = new TextArea("biography",new PropertyModel<String>(getDefaultModel(), "biography"));
			add(biography);
			
			List<Books> bookList =  (List)((Author)getDefaultModelObject()).getBook();
			IModel BookModel = new CompoundPropertyModel<List<Books>>(bookList); 
			@SuppressWarnings("unchecked")
			ListView authorBooks = new ListView("books", BookModel) {
				protected void populateItem(ListItem item) {
					Link view = new Link("authorView", item.getModel()) {
						public void onClick() {
							setResponsePage(new ViewBook(
									(Books) getModelObject()));
						}
					};
					view.add(new Label("name", new PropertyModel(item.getModel(),"name")));
					item.add(view);

				}
			};
			add(authorBooks);
		}

		private int getAuthorId() {
			return author.getUserId();
		}
		
		@Override
		protected void onSubmit() {
			WicketApplication.get().getInvertedIndexDao().updateBiography(((Author)getDefaultModelObject()).getUserId(),((Author)getDefaultModelObject()).getBiography());
		}
		
	}

}
